<template>
  <div style="width: 100%">
    <el-date-picker
      style="width: 100%; height: 100%"
      :type="type"
      v-bind="$attrs"
      v-model="state.paramVal"
      clearable
      :start-placeholder="
        (typeof $attrs.disabled !== 'undefined' && $attrs.disabled !== false) ||
        state.formView
          ? ''
          : $attrs.placeholder
            ? $attrs.placeholder + '起始'
            : `请选择${label}起始`
      "
      :end-placeholder="
        (typeof $attrs.disabled !== 'undefined' && $attrs.disabled !== false) ||
        state.formView
          ? ''
          : $attrs.placeholder
            ? $attrs.placeholder + '终止'
            : `请选择${label}终止`
      "
      :placeholder="
        (typeof $attrs.disabled !== 'undefined' && $attrs.disabled !== false) ||
        state.formView
          ? ''
          : $attrs.placeholder
            ? $attrs.placeholder
            : `请选择${label}`
      "
      :valueFormat="valueFormatCpt"
      :format="formatCpt"
      unlink-panels
      :disabled="isValue($attrs.disabled) ? $attrs.disabled : state.formView"
    >
      <template #default="cell">
        <slot name="default" :cell="cell"></slot>
      </template>
    </el-date-picker>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, watch, inject } from 'vue'
import { isValue } from '@/utils/czr-util'
const emit = defineEmits(['emitParam'])
const props = defineProps({
  param: {},
  label: {},
  type: {
    type: String,
    default: 'date',
    validator(val: string) {
      return [
        'date',
        'year',
        'week',
        'month',
        'dates',
        'monthrange',
        'daterange',
      ].includes(val)
    },
  },
  valueFormat: { type: [String, Boolean], default: false },
  format: { type: String, default: '' },
})
const state = reactive({
  paramVal: props.param,
  formView: inject('form-view', false),
})
watch(
  () => state.paramVal,
  (n) => {
    emit('emitParam', n)
  },
)
watch(
  () => props.param,
  (n) => {
    state.paramVal = n
  },
)
const formatCpt = computed(() => {
  let val = props.format
  if (!val && val !== undefined) {
    switch (props.type) {
      case 'year':
        val = 'YYYY'
        break
      case 'month':
        val = 'YYYY-MM'
        break
      case 'week':
        val = '[第]ww[周]'
        break
      default:
        val = 'YYYY-MM-DD'
    }
  }
  return val
})
const valueFormatCpt = computed(() => {
  let val = props.valueFormat
  if (val === false) {
    switch (props.type) {
      case 'year':
        val = 'YYYY'
        break
      case 'month':
        val = 'YYYY-MM'
        break
      case 'week':
        val = ''
        break
      default:
        val = 'YYYY-MM-DD'
    }
  }
  return val
})
</script>

<style scoped lang="scss">
:deep(.el-range-editor) {
  .el-range-input {
    flex: 1;
  }
  .el-range-separator {
    flex: unset !important;
  }
}
</style>
